// pages/area/spain/spain.js
import evn from "../../../utils/http/evn"
import api from '../../../utils/http/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgBaseUrl:  evn.dev.imgUrl,
    value: '0',
    semesterList: ['春季开学', '秋季开学', '全部'],
    semesterIndex: -1,
    eduPlanList: [
      { label: '高升本', value: 0, id: 1 },
      { label: '本升硕', value: 1, id: 2 },
      { label: '专升硕', value: 2, id: 3 },
      { label: '硕升博', value: 3, id: 4 },
      { label: '专升本', value: 4, id: 5 },
    ],
    placeId: 2,
    openingDateId: '',
    eduPlanId: 1,
    schoolList: [],
    semesterPickerVisible: false,
    selectedSemester: '',
    semesterPopupVisible: false,
    semesterCheckedList: [],
    showTabs: [], // 动态tab选项
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    stickyShowHeight: 30,
    commingSoonVisible:false,
    showSticky: false,
    stickyVisible: false
  },

 onLoad() {
  this.setData({
    openingDateId: '',
    apiOpeningDateId: "1,2", // 默认全选
    semesterCheckedList: ['1', '2'] // 默认全选
  });
  console.log('onLoad触发，placeId:', this.data.placeId);
  this.getEduPlanTabsByArea(() => {
    this.querySchools();
  });
},
onPageScroll(e) {
  // e.scrollTop 是当前滚动高度
 const scrollTop = e.scrollTop;
    // 设置一个阈值，例如滚动超过200px时显示吸顶
    if (scrollTop > 100 && !this.data.showSticky) {
      this.setData({ 
        showSticky: true
      });
      // 添加小延迟，确保DOM先渲染，然后再添加可见性类
      setTimeout(() => {
        this.setData({
          stickyVisible: true
        });
      }, 50);
    } 
    else if (scrollTop <= 100 && this.data.showSticky) {
      // 先执行动画，然后移除元素
      this.setData({ 
        stickyVisible: false
      });
      setTimeout(() => {
        this.setData({
          showSticky: false
        });
      }, 300); // 与CSS过渡时间相同
    }
},

commingSoon(e){
  const url=e.currentTarget.dataset.url
  console.log(url);
  if (url=='request') {
    wx.navigateTo({
      url: '/pages/area/spain/spainRequest',
    })
  }else{
   wx.navigateTo({
     url: '/pages/area/spain/spainLive',
   })
  }
   // this.setData({
   //   commingSoonVisible:true
   // })
 },
onVisibleChange(){
  this.setData({
    commingSoonVisible:false
  })
},
  // 根据地区获取培养计划选项
  getEduPlanTabsByArea(cb) {
    const placeId = this.data.placeId;
    console.log('调用apiGetEduPlanByArea，placeId:', placeId);
    api.apiGetEduPlanByArea({ placeId }).then(res => {
      console.log('apiGetEduPlanByArea返回：', res);
      // res.data 是后端返回的去重后的eduPlanId数组
      const eduPlanIds = Array.isArray(res.data) ? res.data : [];
      this.updateShowTabs(eduPlanIds);
      if (typeof cb === 'function') cb();
    });
  },

  // tab切换
  onTabsChange(e) {
    const idx = Number(e.detail.value);
    const eduPlanId = this.data.eduPlanList[idx].id;
    this.setData({
      value: e.detail.value,
      eduPlanId,
      openingDateId: '',
      apiOpeningDateId: '',
      semesterCheckedList: [],
      pageNum: 1,
      schoolList: [],
      hasMore: true
    }, this.querySchools);
  },

  // picker选择
  onSemesterChange(e) {
    const idx = Number(e.detail.value);
    this.setData({
      semesterIndex: idx,
      openingDateId: idx === 0 ? 1 : 2,
      pageNum: 1,
      schoolList: [],
      hasMore: true
    }, this.querySchools);
  },

  // 查询学校
 querySchools() {
     const { placeId, openingDateId, eduPlanId, apiOpeningDateId, pageNum, pageSize, schoolList } = this.data;
     const params = {
       placeId,
       openingDates: apiOpeningDateId || openingDateId || '',
       eduPlanId,
       pageNum,
       pageSize,
       isShow:1 // 只显示已发布的
     };
     console.log('请求参数:', params);
     api.apiGetProfessionsBySchool(params).then(res => {
       const eduPlanMap = {
         1: '高升本',
         2: '本升硕',
         3: '专升硕',
         4: '硕升博',
         5: '专升本',
       };
       const semesterMap = {
         1: '春季开学',
         2: '秋季开学',
         3: '春秋季开学',
       };
       const placeMap = {
         1: '韩国',
         2: '西班牙',
         3: '新加坡',
         4: '中外合办',
         5: '港澳专区',
       };
       let list = res.data || [];
       list = list.map(item => {
         let openingDateNames = [];
         if (typeof item.openingDates === 'string') {
           const arr = item.openingDates.split(',').map(s => s.trim());
           if (arr.length === 2 && arr.includes('1') && arr.includes('2')) {
             openingDateNames = ['春季开学', '秋季开学'];
           } else if (arr.length === 1) {
             if (arr[0] === '1') openingDateNames = ['春季开学'];
             else if (arr[0] === '2') openingDateNames = ['秋季开学'];
           } else if (arr.length === 1 && arr[0] === '') {
             openingDateNames = [];
           }
         }
         item.intro = this.filterHtmlTags(item.intro);
         let pics = item.pics || '';
         if (Array.isArray(pics)) {
           pics = pics[0] || '';
         } else if (typeof pics === 'string' && pics.includes(',')) {
           pics = pics.split(',')[0];
         }
         // 核心修改：仅处理name字段，超过15字符加省略号，否则用原name
         const processedName = item.name && item.name.length > 12 
           ? item.name.substring(0, 12) + '...' 
           : (item.name || '');
         return {
           ...item,
           name: processedName, // 替换为处理后的名称
           intro: item.intro || '',
           logo: item.logo || '',
           pics: pics,
           eduPlanName: eduPlanMap[item.eduPlanId] || '',
           openingDateNames,
           placeName: placeMap[item.placeId] || '',
         };
       });
       let newList = pageNum > 1 ? schoolList.concat(list) : list;
       this.setData({
         schoolList: newList,
         hasMore: list.length === pageSize
       }, () => {
         wx.createSelectorQuery().select('.school-list-container').boundingClientRect(rect => {
           wx.getSystemInfo({
             success: res => {
               if (rect && rect.height < res.windowHeight && this.data.hasMore) {
                 this.setData({ pageNum: this.data.pageNum + 1 }, this.querySchools);
               }
             }
           })
         }).exec();
       });
     });
   },
  // 动态生成tab选项
  updateShowTabs(eduPlanIds) {
    // tab映射表
    const tabMap = [
      { label: '高升本', value: 0, id: 1 },
      { label: '本升硕', value: 1, id: 2 },
      { label: '专升硕', value: 2, id: 3 },
      { label: '硕升博', value: 3, id: 4 },
      { label: '专升本', value: 4, id: 5 },
    ];
    // 只保留后端返回的id对应的tab
    const showTabs = tabMap.filter(tab => eduPlanIds.includes(tab.id));
    // 默认选中第一个tab
    let value = showTabs.length > 0 ? showTabs[0].value : 0;
    let eduPlanId = showTabs.length > 0 ? showTabs[0].id : 1;
        //如果showTabs.length为0，则添加id是0和1的两个标签
    //如果showTabs.length为1，则添加除了showTabs[0].id之外的第一个标签
    if (showTabs.length === 0) {
      showTabs.push(tabMap[0], tabMap[1]);
      value = 0;
      eduPlanId = 1;
    } else if (showTabs.length === 1) {
      const firstTab = tabMap.find(tab => tab.id !== showTabs[0].id);
      if (firstTab) {
        showTabs.push(firstTab);
      }
    }
    this.setData({ showTabs, value, eduPlanId });
  },

  showSemesterPicker() {
    this.setData({ semesterPickerVisible: !this.data.semesterPickerVisible });
  },
  selectSemester(e) {
    const value = e.currentTarget.dataset.value;
    let openingDateId = '';
    if (value === '春季开学') openingDateId = 1;
    if (value === '秋季开学') openingDateId = 2;
    if (value === '全部') openingDateId = '';
    this.setData({
      selectedSemester: value,
      openingDateId: openingDateId,
      semesterPickerVisible: false,
      pageNum: 1,
      schoolList: [],
      hasMore: true
    }, this.querySchools);
  },

  // 弹出层显示
  showSemesterPopup() {
    this.setData({ semesterPopupVisible: true });
  },
  // 弹出层关闭
  onSemesterPopupChange(e) {
    this.setData({ semesterPopupVisible: e.detail.visible });
  },
  // 取消按钮
  onSemesterCancel() {
    this.setData({ semesterPopupVisible: false });
  },
  onSemesterCheckboxChange(e) {
  const checked = e.detail.value;
  if (checked.length === 0) {
    wx.showToast({
      title: '至少选择一个开学时间',
      icon: 'none'
    });
    return;
  }
  let apiOpeningDateId = '';
  if (checked.length === 2) {
    apiOpeningDateId = "1,2";
  } else if (checked[0] === '1') {
    apiOpeningDateId = 1;
  } else if (checked[0] === '2') {
    apiOpeningDateId = 2;
  } else {
    apiOpeningDateId = '';
  }
  this.setData({
    semesterCheckedList: checked,
    apiOpeningDateId,
    pageNum: 1,
    schoolList: [],
    hasMore: true
  }, this.querySchools);
},
  goBack(){
    wx.navigateBack();
  },
  goSchool(e){
    const id = e?.currentTarget?.dataset?.schoolid || 81;
    wx.navigateTo({
      url: '/pages/schools/schools?schoolId=' + id,
    })
  },
    //过滤html标签
  filterHtmlTags(html) {
    if (!html) return '';
    return html.replace(/<[^>]+>/g, '').replace(/&nbsp;/g, ' ').trim();
  },
  closeCommingSoonPopup() {
  this.setData({
    commingSoonVisible: false
  });
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({ pageNum: 1, schoolList: [], hasMore: true }, this.querySchools);
    wx.stopPullDownRefresh && wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.hasMore) return;
    this.setData({ pageNum: this.data.pageNum + 1 }, this.querySchools);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
})